package org.jeecg.demo.wx.common;

import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 功能描述
 * 小程序用户信息上下文
 *
 * @author: zgq
 * @date: 2024年01月29日 15:57
 */
public class WXUserContext {
    private static final ThreadLocal<WXUserInfo> wxUserInfoThreadLocal = new ThreadLocal<>();

    public static WXUserInfo get() {
        return wxUserInfoThreadLocal.get();
    }

    public static void set(WXUserInfo wxUserInfo) {
        wxUserInfoThreadLocal.set(wxUserInfo);
    }

    public static void remove() {
        wxUserInfoThreadLocal.remove();
    }

    public static String getOpenId() {
        WXUserInfo wxUserInfo = get();
        if (Objects.isNull(wxUserInfo) || StringUtils.isBlank(wxUserInfo.getOpenid())) {
            throw new RuntimeException("用户信息为空");
        }
        return wxUserInfo.getOpenid();
    }

    public static String getSessionKey() {
        WXUserInfo wxUserInfo = get();
        if (Objects.isNull(wxUserInfo) || StringUtils.isBlank(wxUserInfo.getSessionKey())) {
            throw new RuntimeException("用户信息为空");
        }
        return wxUserInfo.getSessionKey();
    }
}
